import re

from application import app
from flask import request, redirect, g

from common.libs.Restful import Restful
from common.models.members import Member
from common.libs.MemberService import MemberService
'''
api认证
'''

@app.before_request
def before_request():
    api_ignore_urls = app.config['API_IGNORE_URLS']
    path = request.path

    ingore_check_login_urls = app.config['IGNORE_CHECK_LOGIN_URLS']
    pattern = re.compile('%s' % '|'.join(ingore_check_login_urls))
    if '/api' not in path:
        return
    if pattern.match(path):
        return
    pattern = re.compile('%s' % '|'.join(api_ignore_urls))
    if pattern.match(path):
        return

    member_info = check_member_login()
    g.member_info = None
    if member_info:
        g.member_info = member_info

    if not member_info:
        return Restful.token_expri_error()

    return

'''
判断用户是否已经登录
'''
def check_member_login():
    auth_token = request.headers.get('Authorization')
    if auth_token is None:
        return False
    auth_info = auth_token.split('#')
    if len(auth_info) != 2:
        return False
    try:
        member_info = Member.Member.query.filter_by(id=int(auth_info[1])).first()
    except Exception:
        return False
    if not member_info:
        return False
    if '%s#%s'%(MemberService.MemberService.geneAuthCode(member_info), member_info.id) != auth_token:
        return False
    if member_info.status != 1:
        return False
    return member_info